package cloud.common;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.util.Properties;

/**
 * @classDesc: 功能描述:(mybatis配置文件)
 * @author: 顾理想
 * @createTime: 2017年10月17日 15:53
 * @version: v1.0
 * @copyright:善林科技
 */
@Configuration
@PropertySource("classpath:application-${spring.profiles.active}.properties")
public class MyBatisConfig {
    @Autowired
    private Environment environment ;

    @Value("${cg.properties.driverClass}")
    private String driverClass;

    @Value("${cg.properties.url}")
    private String url;

    @Value("${cg.properties.password}")
    private String password;

    @Value("${cg.properties.username}")
    private String username;

    @Value("${mybatis.typeAliasesPackage}")
    private String typeAliasesPackage;

    @Value("${mybatis.mapperLocations}")
    private String mapperLocations;


    /**
     *
     * 创建数据源
     */
    @Bean
    public DataSource getDataSource() throws Exception {
        Properties properties = new Properties() ;
        properties.put("driverClassName",driverClass) ;
        properties.put("url", url) ;
        properties.put("username",username) ;
        properties.put("password", password) ;
        return DruidDataSourceFactory.createDataSource(properties) ;
    }

    /**
     * 根据数据源创建SqlSessionFactory
     */
    @Bean
    public SqlSessionFactory getSqlSessionFactory(DataSource dataSource) throws Exception {

        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean() ;
        sqlSessionFactoryBean.setDataSource(dataSource) ;
        //下边两句仅仅用于*.xml文件，如果整个持久层操作不需要使用到xml文件的话（只用注解就可以搞定），则不加
        sqlSessionFactoryBean.setTypeAliasesPackage(typeAliasesPackage);//指定基包
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapperLocations));//指定xml文件位置
        //把数据库的下划线列映射到javabean的驼峰属性上  顾理想 add by 2017-5-9
        sqlSessionFactoryBean.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);
        return sqlSessionFactoryBean.getObject() ;
    }
}
